package com.jumei.flume.common;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PageUtils {
    private final static Logger logger = LoggerFactory.getLogger(PageUtils.class);
    /**
     * 解析store_id
     * 规则：
     * material_item_id抽取规则：regexp_extract(p__url,'.*(/store/|store_id=|storeId=)([0-9]+).*',2)
     *
     * @param url
     * @return
     * @author admin
     * @since 2017年4月12日
     */
    public static String parseStoreId(String url) {
        if (url == null) {
            return null;
        }
        Pattern p = Pattern.compile(".*(/store/|store_id=|storeId=)([0-9]+).*");
        Matcher m = p.matcher(url);
        if (m.find()) {
            return m.group(2);
        }
        return null;
    }

    public static List<String[]> parseUrlFields(String url) {
        url = decodeUrl(url);//中文解码

        int indexOfQuery = url.indexOf('?');
        List<String[]> fields = new ArrayList<String[]>();
        try {
            if (indexOfQuery > 0) {
                String query = url.substring(indexOfQuery + 1);
                String[] pairs = query.split("&");
                for (String pair : pairs) {
                    int idx = pair.indexOf("=");
                    if (idx == -1) {
                        continue;
                    }
                    /**
                     * BUG FIX @author admin
                     * 20170322
                     */
                    String key = URLDecoder.decode(pair.substring(0, idx).replaceAll("%", "%25"), "UTF-8");
                    String value = URLDecoder.decode(pair.substring(idx + 1).replaceAll("%", "%25"), "UTF-8");

                    //BUG #156940
                    //兼容：jumeimall://page/web?url=http://h5.jumei.com/product/detail?item_id=d171031p2247248ys&type=jumei_deal&selltype=jmstore_h5&selllabel=171111yushou_app&selllabel=20171111cosmetic_1208_app_hot_4819268&frompageattri=&position=2&module_id=4819268&activity_symbol=20171111cosmetic_1208_app
                    //兼容：http://6206.h5.jmeinet.com/wxs/index?base_url=http://2465.fd.jumei.com/yiqituan/detailSecret?item_id=ht180723p1431467t4&type=global_deal&tid=51435524&share_source=app&from=timeline
                    if (key.equalsIgnoreCase("url") || key.equalsIgnoreCase("base_url")) {
                        String[] __item_id = value.split("item_id=");
                        if (__item_id.length > 1) {
                            fields.add(new String[]{"item_id", __item_id[1]});
                        }
                    }

                    fields.add(new String[]{key.toLowerCase(), value});
                }
            }
        } catch (Exception e) {
            // 处理解析失败
            logger.warn("Parse url failed, record: " + url, e);
        }
        return fields;
    }

    public static Map<String, String> parseUrlFields4Map(String url) {
        //中文解码
        url = decodeUrl(url);

        int indexOfQuery = url.indexOf('?');
        Map<String, String> fields = Maps.newHashMap();
        try {
            if (indexOfQuery > 0) {
                String query = url.substring(indexOfQuery + 1);
                String[] pairs = query.split("&");
                for (String pair : pairs) {
                    int idx = pair.indexOf("=");
                    if (idx == -1) {
                        continue;
                    }
                    /**
                     * BUG FIX @author admin
                     * 20170322
                     */
                    String key = URLDecoder.decode(pair.substring(0, idx).replaceAll("%", "%25"), "UTF-8");
                    String value = URLDecoder.decode(pair.substring(idx + 1).replaceAll("%", "%25"), "UTF-8");

                    //BUG #156940
                    //兼容：jumeimall://page/web?url=http://h5.jumei.com/product/detail?item_id=d171031p2247248ys&type=jumei_deal&selltype=jmstore_h5&selllabel=171111yushou_app&selllabel=20171111cosmetic_1208_app_hot_4819268&frompageattri=&position=2&module_id=4819268&activity_symbol=20171111cosmetic_1208_app
                    //兼容：http://6206.h5.jmeinet.com/wxs/index?base_url=http://2465.fd.jumei.com/yiqituan/detailSecret?item_id=ht180723p1431467t4&type=global_deal&tid=51435524&share_source=app&from=timeline
                    if (key.equalsIgnoreCase("url") || key.equalsIgnoreCase("base_url")) {
                        String[] __item_id = value.split("item_id=");
                        if (__item_id.length > 1) {
                            fields.put("item_id", __item_id[1]);
                        }

                    }

                    fields.put(key.toLowerCase(), value);//兼容大小写
                }
            }
        } catch (Exception e) {
            // 处理解析失败
            logger.warn("Parse url failed, record: " + url, e);
        }
        return fields;
    }

    /**
     * deocode url
     * <p>
     * 产品需求 #155571
     * https://echo.int.jumei.com/issues/155571
     * <p>
     * 样例：
     * jumeimall://page/web?url=http%3A%2F%2Fh5.jumei.com%2Fs%2Fact%2F616dyc_app.html
     *
     * @param url
     * @return
     * @author admin
     * @since 2018年7月10日
     */
    public static String decodeUrl(String url) {
        if (Strings.isNullOrEmpty(url)) {
            return "";
        }

        try {
            if (isEncodeUrl(url)) {
                String parsedUrl = URLDecoder.decode(url, "UTF-8");
                return parsedUrl;
            }

        } catch (Exception e) {
            // say something here
        }

        return url;
    }

    /**
     * 判断url是否被encode
     * <p>
     * url中包含 %
     * jumeimall://page/web?url=http%3A%2F%2Fh5.jumei.com%2Fs%2Fact%2F616dyc_app.html
     *
     * @param url
     * @return
     * @author admin
     * @since 2018年7月10日
     */
    private static boolean isEncodeUrl(String url) {
        return url.contains("%");
    }

    /**
     * 获取专场标示
     *
     * @param url
     * @return
     */
    public static String getLabelName(String url) {
        if (Strings.isNullOrEmpty(url)) {
            return null;//null checker
        }

        String pattern = ".*(&|\\?)label=(\\S+?)(&|$).*";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(url);
        if (m.find()) {
            return m.group(2);
        }
        pattern = ".*/(\\S+?)\\.htm.*";
        p = Pattern.compile(pattern);
        m = p.matcher(url);
        if (m.find()) {
            return m.group(1);
        }
        return null;
    }

    static List<Pattern> activity_regx = Lists.newArrayList(
            Pattern.compile(".*page/activity/detail.*"),
            Pattern.compile(".*jumei.com(/act/|/s/act/)(.*).html.*"),
            Pattern.compile(".*(&|\\?)label=(\\S+?)(&|$).*"),
            Pattern.compile(".*jumei.com/activity/detailv2.*"));

    /**
     * 判断是否为专场
     *
     * @param url
     * @return
     */
    public static boolean checkActivity(String url) {
        if (Strings.isNullOrEmpty(url))
            return Boolean.FALSE;

        for (Pattern p : activity_regx) {
            if (p.matcher(url).matches()) {
                return Boolean.TRUE;
            }
        }

        return Boolean.FALSE;
    }


    /**
     * 获取url path
     * jumeimall://page/search?search=意大利维纳斯补水面膜&searchWordType=inputword -> jumeimall://page/search
     *
     * @param url
     * @return
     */
    public static String getUrlPath(String url) {
        if (Strings.isNullOrEmpty(url)) {
            return "";
        }

        int idx = url.indexOf("?");
        if (idx > 0) {
            url = url.substring(0, idx);
        }

        return url;
    }


    /**
     * 统一兼容item_id, itemid
     *
     * @param url
     * @return
     */
    public static String getItemId(String item_id, String url) {
        if (Strings.isNullOrEmpty(url)) return null;//null checker

//		if( ! Strings.isNullOrEmpty(item_id)) {
//			return item_id;
//		}

        Map<String, String> fields = parseUrlFields4Map(url);
        if (fields.containsKey("item_id")) {
            return fields.get("item_id");
        }

        if (fields.containsKey("itemid")) {
            return fields.get("itemid");
        }
        //兼容：https://h5.jumei.com/s/coutuan/df1804246750996p4062474-jumei_pop.html?&selltype=jmstore_h5&selllabel=zy_weixinqun_20171228&sellparams=page_id:5487129
        Pattern r = Pattern.compile(".*/s/coutuan/(.*)-(.*)\\.html.*");
        Matcher coutuan = r.matcher(url);
        while (coutuan.find()) {
            return coutuan.group(1);
        }

        return "";
    }
}
